<?php
include('conect.php');
$con = mysql_connect($hostname, $username, $password) or die('Could not connect: ' . mysql_error());
//select database
mysql_select_db($database, $con);
mysql_query("SET NAMES utf8");  

if ($_POST['acction'] === 'login') {
	$email = $_POST['email'];
	$pass = $_POST['pass'];
	$sql = "SELECT id, email FROM user WHERE email='$email' AND pass='$pass'";
	$rs = mysql_query($sql);
	$info = array();
	//$n = mysql_num_rows($rs);
	
	while($obj = mysql_fetch_object($rs)) {
		$info[] = $obj;
	}
	if(mysql_num_rows($rs) > 0){
		$arr = array('success' => true,'rows'  => $info );
	}else{
		$info[] = array('id' => false,'task'  => 'Login failed. Try again.');
		$arr = array('success' => false,'rows'  => $info);
	}
}

if ($_POST['acction'] === 'regis') {
	$pass = $_POST['pass'];
	$rpass = $_POST['rpass'];
	$email = $_POST['email'];
	$info = array();
if($pass == $rpass){

	$rs = mysql_query("SELECT * FROM user WHERE email='$email'");
    if(mysql_num_rows($rs) > 0){
         $info[] = array('id' => false,'task'  => 'Registration failed. This email exist. Try again.');
         $arr = array('success' => false,'rows'  => $info);
    } else {
        $rs = mysql_query("INSERT INTO user (email,pass) VALUES ('$email','$pass')");

        $sql = "SELECT id, email FROM user WHERE email='$email' AND pass='$pass'";
        $rs = mysql_query($sql);
        $info = array();
        $u;
        while($obj = mysql_fetch_object($rs)) {
            $info[] = $obj;
            $u=$obj->id;
        }
        //Se insereaza tipurile default pentru userul dat
        $rss = mysql_query("INSERT INTO tip (task,it,user,cr,sens) VALUES ('Cheltuieli','1','$u','1','0'),('Venituri','2','$u','2','1'),('Zeciuiala','3','$u','3','0'),('Mi-a dat','4','$u','4','1'),('Am dat','5','$u','5','0')");
        if(mysql_num_rows($rs) > 0){
            $info[] = array('id' => 'Info','task'  => 'You have successfully registered. Logati-va!');
            $arr = array('success' => true,'rows'  => $info);
        }else{
            $info[] = array('id' => false,'task'  => 'Registration failed. Try again.');
            $arr = array('success' => false,'rows'  => $info);
        }
	}
}else{
	$info[] = array('id' => false,'task'  => 'Passwords are not equal. Try again.');
	$arr = array('success' => false,'rows'  => $info);
}
}

mysql_close($con);
echo json_encode($arr);
?>